//
//  BulletSettingView.swift
//  SkyApp
//
//  Created by 白翊 on 2021/12/20.
//

import UIKit

protocol BulletSettingViewProtocol: NSObjectProtocol {
    func updateBullet()
}

class BulletSettingView: UIView {

    let HEADER_HEIGHT = NAVBAR_HEIGHT + 320
    let itemHeight: CGFloat = 50
    
    weak var delegate: BulletSettingViewProtocol?
    
    class func showInWindow(delegate: BulletSettingViewProtocol?) {
        let rootView = AppTool.rootView()
        rootView?.endEditing(true)
        
        let view = BulletSettingView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: HEIGHT))
        view.delegate = delegate
        rootView?.addSubview(view)
        
        view.show()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        reloadUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func reloadUI() {
        headerView.removeAllSubviews()
        
        let weights = [BulletSettingWeight.bold.rawValue, BulletSettingWeight.medium.rawValue, BulletSettingWeight.light.rawValue, BulletSettingWeight.thin.rawValue]
        let weightsView = createItems(top: NAVBAR_HEIGHT, title: "字重:", items: weights, index: weights.firstIndex(of: bulletWeight.rawValue) ?? 0) { [weak self] index in
            bulletWeight = BulletSettingWeight(rawValue: weights[index]) ?? .medium
            self?.delegate?.updateBullet()
        }
        
        let sizes = [BulletSettingSize.superLarge.rawValue, BulletSettingSize.large.rawValue, BulletSettingSize.medium.rawValue, BulletSettingSize.small.rawValue]
        let sizesView = createItems(top: weightsView.bottom, title: "字号:", items: sizes, index: sizes.firstIndex(of: bulletSize.rawValue) ?? 0) { [weak self] index in
            bulletSize = BulletSettingSize(rawValue: sizes[index]) ?? .medium
            self?.delegate?.updateBullet()
        }
        
        let speeds = [BulletSettingSpeed.fast.rawValue, BulletSettingSpeed.medium.rawValue, BulletSettingSpeed.slow.rawValue]
        let speedsView = createItems(top: sizesView.bottom, title: "字速:", items: speeds, index: speeds.firstIndex(of: bulletSpeed.rawValue) ?? 0) { [weak self] index in
            bulletSpeed = BulletSettingSpeed(rawValue: speeds[index]) ?? .medium
            self?.delegate?.updateBullet()
        }
        
        let bgColors = [UIColor.bg, UIColor(hexString: "#ffffff")!, UIColor(hexString: "#6bcff9")!, UIColor(hexString: "#6bf9bf")!, UIColor(hexString: "#f9cc6b")!, UIColor(hexString: "#f84545")!]
        let bgColorsView = createColors(top: speedsView.bottom, title: "背景", colors: bgColors, index: bgColors.firstIndex(of: bulletBGColor) ?? 0) { [weak self] color in
            bulletBGColor = color
            self?.delegate?.updateBullet()
        }
        
        let colors = [UIColor.title, UIColor(hexString: "#000000")!, UIColor(hexString: "#6bcff9")!, UIColor(hexString: "#6bf9bf")!, UIColor(hexString: "#f9cc6b")!, UIColor(hexString: "#f84545")!]
        let colorsView = createColors(top: bgColorsView.bottom, title: "弹幕", colors: colors, index: colors.firstIndex(of: bulletColor) ?? 0) { [weak self] color in
            bulletColor = color
            self?.delegate?.updateBullet()
        }
        
        let shadowColors = [UIColor(hexString: "#ffffff")!, UIColor(hexString: "#000000")!, UIColor.theme, UIColor(hexString: "#6bf9bf")!, UIColor(hexString: "#f9cc6b")!, UIColor(hexString: "#f84545")!]
        let _ = createColors(top: colorsView.bottom, title: "阴影", colors: shadowColors, index: shadowColors.firstIndex(of: bulletShadow) ?? 0) { [weak self] color in
            bulletShadow = color
            self?.delegate?.updateBullet()
        }
        
    }
    
    private func createItems(top: CGFloat, title: String, items: [String], index: Int, clickAction: @escaping (Int) -> ()) -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: top, width: WIDTH, height: itemHeight))
        
        let titleLabel = UILabel(string: title, fontSize: 12, frame: CGRect(x: interval, y: 0, width: 48, height: view.height), color: .detail, textAlignment: .left)
        view.addSubview(titleLabel)
        
        let btn_width: CGFloat = (WIDTH - titleLabel.right - interval - interval * 3) * 0.25
        let btn_height: CGFloat = 32
        for (i, name) in items.enumerated() {
            let btn = UIButton(title: name, fontSize: 14, frame: CGRect(x: titleLabel.right + (interval + btn_width) * CGFloat(i), y: (view.height - btn_height) * 0.5, width: btn_width, height: btn_height)) { [weak self] _ in
                if i == index { return }
                clickAction(i)
                self?.reloadUI()
            }
            btn.setCornerRadius(radius: btn_height * 0.5)
            if index == i {
                btn.backgroundColor = .title
                btn.setTitleColor(.bg, for: .normal)
                btn.setBorder(width: 1, color: .clear)
            }else {
                btn.backgroundColor = .clear
                btn.setTitleColor(.remark, for: .normal)
                btn.setBorder(width: 1, color: .line)
            }
            view.addSubview(btn)
        }
        headerView.addSubview(view)
        
        return view
    }
    
    private func createColors(top: CGFloat, title: String, colors: [UIColor], index: Int, clickAction: @escaping (UIColor) -> ()) -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: top, width: WIDTH, height: itemHeight))
        
        let titleLabel = UILabel(string: title, fontSize: 12, frame: CGRect(x: interval, y: 0, width: 48, height: view.height), color: .detail, textAlignment: .left)
        view.addSubview(titleLabel)
        
        let btn_size: CGFloat = 32
        let btn_interval = (WIDTH - titleLabel.right - interval - btn_size * CGFloat(colors.count - 1)) / CGFloat(colors.count)
        for (i, color) in colors.enumerated() {
            let btn = UIButton(type: .custom)
            btn.frame = CGRect(x: titleLabel.right + (btn_interval + btn_size) * CGFloat(i), y: (view.height - btn_size) * 0.5, width: btn_size, height: btn_size)
            btn.addBlock(for: .touchUpInside) { [weak self] _ in
                if i == index { return }
                clickAction(color)
                self?.reloadUI()
            }
            btn.setCornerRadius(radius: btn_size * 0.5)
            btn.backgroundColor = color
            if index == i {
                btn.setBorder(width: 3, color: .detail)
            }else {
                btn.setBorder(width: 0, color: .clear)
            }
            view.addSubview(btn)
        }
        headerView.addSubview(view)
        
        return view
    }
    
    private func show() {
        self.maskBGView.alpha = 0
        self.headerView.snp.updateConstraints { (make) in
            make.top.equalTo(-HEADER_HEIGHT)
        }
        self.layoutIfNeeded()
        
        self.headerView.snp.updateConstraints { (make) in
            make.top.equalTo(0)
        }
        
        UIView.animate(withDuration: 0.32, animations: {
            self.maskBGView.alpha = 0.72
            self.layoutIfNeeded()
        }) { (complete) in
            
        }
    }
    
    @objc private func disappear() {
        self.maskBGView.alpha = 0.72
        self.headerView.snp.updateConstraints { (make) in
            make.top.equalTo(-HEADER_HEIGHT)
        }
        
        UIView.animate(withDuration: 0.32, animations: {
            self.alpha = 0
            self.layoutIfNeeded()
        }) { (complete) in
            self.removeFromSuperview()
        }
    }
    
    lazy var headerView:UIView = {
        let view = UIView()
        view.backgroundColor = .bg.withAlphaComponent(0.8)
        self.insertSubview(view, aboveSubview: self.maskBGView)
        
        view.snp.makeConstraints({ (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(-HEADER_HEIGHT)
            make.height.equalTo(HEADER_HEIGHT)
        })
        
        return view
    }()
    
    lazy var maskBGView:UIView = {
        let maskBGView = UIView()
        maskBGView.backgroundColor = .shadow
        maskBGView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(disappear)))
        self.addSubview(maskBGView)
        
        //实现模糊效果
        let effect = UIBlurEffect.init(style: UIColor.darkMode ? .dark : .light)
        let effectView = UIVisualEffectView.init(effect: effect)
        maskBGView.addSubview(effectView)
        
        maskBGView.snp.makeConstraints({ (make) in
            make.edges.equalTo(self)
        })
        
        effectView.snp.makeConstraints({ (make) in
            make.edges.equalTo(maskBGView)
        })
        
        return maskBGView
    }()
    
}
